/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.liycloud.common.security.component;

import com.liycloud.common.security.annotation.Inner;

import cn.hutool.core.util.ReUtil;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Pattern;

/**
 * @date 2019/4/13
 * <p>
 * 资源服务器对外直接暴露URL,如果设置 context-path 要特殊处理
 * <p>
 * 首先，在我们项目加载阶段，我们获取有Inner注解的类和方法，然后获取我们配置的uri，
 * 经过正则替换后面的可变参数为*，然后将此uri加入到ignore-url中。
 * 此时我们就能达到所有 @Inner 配置的方法/类上的接口地址，
 * <p>
 * 都统一在项目加载阶段自动帮我们加到ignore-url中，
 * <p>
 * 不需要我们手动配置，免去了很多开发工作，
 * 同时也能避免我们忘记配置，而浪费开发时间。
 */
@Slf4j
@Configuration
@RequiredArgsConstructor
@ConditionalOnExpression("!'${security.oauth2.client.ignore-urls}'.isEmpty()")   // 不为空时生效

@ConfigurationProperties(prefix = "security.oauth2.client") // 关联配置文件的拿个节点;
public class PermitAllUrlProperties implements InitializingBean {

	private static final Pattern PATTERN = Pattern.compile("\\{(.*?)\\}");

	private final WebApplicationContext applicationContext;

	@Getter
	@Setter  // 对应 ignore-urls 节点
	private List<String> ignoreUrls = new ArrayList<>();


	/**
	*  将配置文件中 security.oauth2.client.ignore-urls 的配置内容赋值给 PermitAllUrlProperties 的实例Bean
	*
	**/
	@Override
	public void afterPropertiesSet() {
		RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
		Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();

		for (RequestMappingInfo info : map.keySet()) {
			HandlerMethod handlerMethod = map.get(info);

			// 获取方法上边的注解 替代 path variable 为 *
			Inner method = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), Inner.class);

			Optional.ofNullable(method).ifPresent(inner -> {
				for (String url : info.getPatternsCondition().getPatterns()) {
					ignoreUrls.add(ReUtil.replaceAll(url, PATTERN, "*"));
				}
			});

			// 获取类上边的注解, 替代path variable 为 *
			Inner controller = AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), Inner.class);

			Optional.ofNullable(controller).ifPresent(inner -> {
				for (String url : info.getPatternsCondition().getPatterns()) {
					ignoreUrls.add(ReUtil.replaceAll(url, PATTERN, "*"));
				}
			});
		}

	}

}
